const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function rad(d) {
    return d * Math.PI / 180.0; 
}

  // 根据经纬度计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
  function getDistance(lat1, lng1, lat2, lng2) {
    // console.log("lat1="+lat1)
    // console.log("lng1="+lng1)
    // console.log("lat2="+lat2)
    // console.log("lng2="+lng2)
    var radLat1 = rad(lat1);
    var radLat2 = rad(lat2);
    var a = radLat1 - radLat2;
    var b = rad(lng1) - rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; //输出为公里

    var distance = s;
    var distance_str = "";

    if (parseInt(distance) >= 1) {
        distance_str = distance.toFixed(1) + "km";
    } else {
        distance_str = distance * 1000 + "m";
    }
    //s=s.toFixed(4);
    // console.info('lyj 距离是', s);
    // console.info('lyj 距离是', distance_str);
    //return (s*1000).toFixed(1); //返回m,小数点后1位
    return Math.floor(s*1000); //这个*2是为了缩小误差
}

function time_range(beginTime, endTime, nowTime){
  var strb = beginTime.split (":");
  if (strb.length != 2) {
      return false;
  }

  var stre = endTime.split (":");
  if (stre.length != 2) {
      return false;
  }

  var strn = nowTime.split (":");
  if (stre.length != 2) {
      return false;
  }
  var b = new Date ();
  var e = new Date ();
  var n = new Date ();

  b.setHours (strb[0]);
  b.setMinutes (strb[1]);
  e.setHours (stre[0]);
  e.setMinutes (stre[1]);
  n.setHours (strn[0]);
  n.setMinutes (strn[1]);

  if (n.getTime () - b.getTime () > 0 && n.getTime () - e.getTime () < 0) {
      return true;
  } else {
      console.log("当前时间是：" + n.getHours () + ":" + n.getMinutes () + "，不在该时间范围内！");
      return false;
  }
}

function time_range_now(beginTime, endTime) {
  var strb = beginTime.split (":");
 
  if (strb.length != 2) {
      return false;
  }

  var stre = endTime.split (":");
 
  if (stre.length != 2) {
      return false;
  }

  var b = new Date ();
  var e = new Date ();
  var n = new Date ();

  b.setHours (strb[0]);
  b.setMinutes (strb[1]);
  e.setHours (stre[0]);
  e.setMinutes (stre[1]);

  if (n.getTime () - b.getTime () > 0 && n.getTime () - e.getTime () < 0) {
      return true;
  } else {
      console.log("当前时间是：" + n.getHours () + ":" + n.getMinutes () + "，不在该时间范围内！");
      return false;
  }
}


module.exports = {
  formatTime,
  getDistance,
  time_range,  //传3个参数
  time_range_now //传2个参数 看当前在不在时间范围内
}